package com.lry.web.fiction.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lry.web.fiction.entity.Fiction;
import com.lry.web.fiction.entity.FictionVariable;
import com.lry.web.fiction.mapper.FictionVariableMapper;
import com.lry.web.fiction.processor.FictionVerifyProcessor;
import com.lry.web.fiction.service.FictionVariableService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import us.codecraft.webmagic.Spider;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FictionVariableServiceImpl implements FictionVariableService {
    @Autowired
    FictionVariableMapper fictionVariableMapper;



    public int setFictionVariable(FictionVariable fictionVariable) {
        int insert = fictionVariableMapper.insert(fictionVariable);
        return insert;
    }


    public List<FictionVariable> getFictionVariables() {
        return fictionVariableMapper.selectList(null);
    }

    public int delete(Integer id) {
        return fictionVariableMapper.deleteById(id);
    }

    public FictionVariable getFictionVariable(Integer id) {
        return fictionVariableMapper.selectById(id);
    }
    //获取全部小说规则，分页
    public Map<String, Object> selectFictionVariables(Integer from, Integer size) {
        Page<FictionVariable> page = new Page<FictionVariable>(from,size);
        fictionVariableMapper.selectPage(page, null);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("fictionVariables",page.getRecords());
        map.put("pages",page.getPages());
        return map;
    }

    public int updateFictionVariable(FictionVariable fictionVariable) {

        return fictionVariableMapper.updateById(fictionVariable);
    }

    public Map<String, Object> verifyFictionVariable(FictionVariable fictionVariable,String name) throws Exception {
        Map<String,Object> map  = new HashMap<String,Object>();
        Spider.create(new FictionVerifyProcessor(fictionVariable,map))
                //设置爬取数据的地址
                .addUrl(fictionVariable.getSearchUrl()+name)
                //执行爬虫
                .thread(5)
                .run();
        return map;
    }

}
